package com.cqc.googleplay.fragment.home;

import java.util.ArrayList;
import java.util.List;

import com.cqc.googleplay.R;
import com.cqc.googleplay.activity.AppDetailActivity;
import com.cqc.googleplay.adapter.BannerPagerAdapter;
import com.cqc.googleplay.adapter.HomeFragAdapter;
import com.cqc.googleplay.application.MyApplication;
import com.cqc.googleplay.bean.AppInfoBean;
import com.cqc.googleplay.bean.HomeFragBean;
import com.cqc.googleplay.http.HttpHelper;
import com.cqc.googleplay.http.NetUrl;
import com.cqc.googleplay.utils.CommonUtil;
import com.cqc.googleplay.utils.GsonUtil;
import com.cqc.googleplay.utils.ToastUtil;
import com.cqc.googleplay.view.ContentPager;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class HomeFrag extends Fragment {

	private View view;
	private PullToRefreshListView ptr;
	private List<String> pictUrlList = new ArrayList<String>();
	private List<String> pictDescList = new ArrayList<String>();
	private List<TextView> dotsList = new ArrayList<TextView>();
	private List<AppInfoBean> appsList = new ArrayList<AppInfoBean>();
	private HomeFragAdapter adapter;
	private ListView listView;
	private static final int WHAT1 = 1;// 下拉
	private static final int WHAT2 = 2;// 上拉
	private static final int WHAT3 = 3;// 轮播图循环
	private ContentPager contentPager;
	private ViewPager viewPager;
	private TextView tv_desc;
	private TextView tv_ratio;
	private LinearLayout ll_dots;
	private View headView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		contentPager = new ContentPager(getActivity()) {

			@Override
			public Object requestData() {
				return getData();
			}

			@Override
			public View createSuccessView() {
				return getSuccessView();
			}
		};
		return contentPager;
	}

	protected View getSuccessView() {
		view = View.inflate(getActivity(), R.layout.frag_home, null);
		ptr = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);
		ptr.setMode(Mode.BOTH);
		ptr.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if (refreshView.getCurrentMode() == Mode.PULL_FROM_START) {// 下拉刷新
					handler.sendEmptyMessageDelayed(WHAT1, 1500);
				} else {// 上拉加载更多
					// handler.sendEmptyMessageDelayed(WHAT2, 1500);//模拟上拉加载更多
					contentPager.loadDataAndRefresh();
				}
			}

		});
		listView = ptr.getRefreshableView();
		adapter = new HomeFragAdapter(appsList);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == 1) {
					ToastUtil.showShortToast("viewpager");
				} else {
					ToastUtil.showShortToast("" + appsList.get(position - 1 - 1).getName());
					Intent intent = new Intent(getActivity(), AppDetailActivity.class);
					intent.putExtra("packageName", appsList.get(position).getPackageName());
					startActivity(intent);
				}
			}
		});
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (viewPager != null) {
			handler.sendEmptyMessage(WHAT3);
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		handler.removeMessages(WHAT3);
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == WHAT1) {
				if (ptr.isRefreshing()) {
					ptr.onRefreshComplete();
				}
			} else if (msg.what == WHAT2) {
				adapter.notifyDataSetChanged();
				if (ptr.isRefreshing()) {
					ptr.onRefreshComplete();
				}
			} else if (msg.what == WHAT3) {
				viewPager.setCurrentItem((viewPager.getCurrentItem() + 1) % pictUrlList.size());
				handler.sendEmptyMessageDelayed(WHAT3, 1500);
			}
		};
	};

	protected Object getData() {
		String json = HttpHelper.get(NetUrl.HOME + appsList.size());
		HomeFragBean bean = GsonUtil.jsonToBean(json, HomeFragBean.class);
		addAndRefreshData(bean);
		return bean;
	}

	private void addAndRefreshData(HomeFragBean bean) {
		if (bean != null) {
			if (bean.getPicture() != null && bean.getPicture().size() > 0) {
				pictUrlList.addAll(bean.getPicture());
				initBanner();
			}

			appsList.addAll(bean.getList());
			// ui线程 更新ui
			CommonUtil.runOnUIThread(new Runnable() {
				@Override
				public void run() {
					adapter.notifyDataSetChanged();
					handler.sendEmptyMessage(WHAT3);
					if (ptr.isRefreshing()) {
						ptr.onRefreshComplete();
					}
				}
			});
		}
	}

	private void initBanner() {
		findHeadViews();
		initPictDescList();
		initDots();

		initViewPager();
	}

	private void initViewPager() {
		BannerPagerAdapter adapter = new BannerPagerAdapter(pictUrlList);
		viewPager.setAdapter(adapter);
		listView.addHeaderView(headView);
		tv_desc.setText("第一张图");
		tv_ratio.setText(1 + "/" + pictUrlList.size());
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				tv_desc.setText(pictDescList.get(position));
				tv_ratio.setText(1 + position + "/" + pictUrlList.size());
				for (int i = 0; i < dotsList.size(); i++) {
					if (i == position) {
						dotsList.get(i).setBackgroundResource(R.drawable.dot_focus);
					} else {
						dotsList.get(i).setBackgroundResource(R.drawable.dot_normal);
					}
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		// 缺点：headView没有点击事件
		listView.requestDisallowInterceptTouchEvent(false);
		headView.setFocusable(true);
		headView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ToastUtil.showShortToast("headView");
			}
		});
	}

	private void findHeadViews() {
		headView = View.inflate(MyApplication.getContext(), R.layout.layout_banner, null);
		viewPager = (ViewPager) headView.findViewById(R.id.viewpager_banner);
		tv_desc = (TextView) headView.findViewById(R.id.tv_desc_banner);
		tv_ratio = (TextView) headView.findViewById(R.id.tv_ratio_banner);
		ll_dots = (LinearLayout) headView.findViewById(R.id.ll_dots);
	}

	private void initDots() {
		ll_dots.removeAllViews();
		dotsList.clear();

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);
		for (int i = 0; i < pictUrlList.size(); i++) {
			TextView tv = new TextView(getActivity());
			if (i == 0) {
				tv.setBackgroundResource(R.drawable.dot_focus);
			} else {
				tv.setBackgroundResource(R.drawable.dot_normal);
			}
			params.setMargins(10, 0, 0, 0);
			ll_dots.addView(tv, params);
			dotsList.add(tv);
		}
	}

	private void initPictDescList() {
		for (int i = 0; i < pictUrlList.size(); i++) {
			pictDescList.add("第" + (i + 1) + "张图");
		}
	}
}
